package com.gem.back.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gem.back.common.StringToDate;
import com.gem.back.entity.AoaAttendsList;
import com.gem.back.entity.AoaStatusList;
import com.gem.back.entity.AoaTypeList;
import com.gem.back.entity.AoaUser;
import com.gem.back.mapper.AoaAttendsListMapper;
import com.gem.back.mapper.AoaTypeListMapper;
import com.gem.back.mapper.AoaUserMapper;
import com.gem.back.service.IAoaAttendsListService;
import com.gem.back.service.IAoaStatusListService;
import com.gem.back.service.IAoaTypeListService;
import com.gem.back.service.IAoaUserService;
import com.gem.utils.TypeDictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  考勤前端控制器
 * </p>
 *
 * @author hhhy
 * @since 2020-02-22
 */
@Controller
@RequestMapping("/")
public class AoaAttendsListController {

    @Autowired
    private IAoaAttendsListService iAoaAttendsListService;

    @Autowired
    private AoaAttendsListMapper attendsListMapper;

    @Autowired
    private IAoaUserService aoaUserService;

    @Autowired
    private AoaTypeListMapper typeListMapper;

    @Autowired
    private IAoaTypeListService typeListService;

    @Autowired
    private IAoaStatusListService statusListService;

    // 格式转化导入
    DefaultConversionService service = new DefaultConversionService();

    //考勤签到
    @RequestMapping("singin")
    public String Datag(Model model, String model1, Integer value, AoaAttendsList aoaAttendsList, HttpServletRequest request, HttpSession session) throws UnknownHostException {
        //获取ip
        InetAddress ina = null;
        ina = ina.getLocalHost();
        String attendIp =ina.getHostAddress();
        //规定上下班时间
        String start ="09:00:00";
        String end = "22:00:00";
        service.addConverter(new StringToDate());
        //默认状态(正常)
        Integer type;
        Integer status = 0;
        AoaAttendsList attendsList = null;

        //读取当前登录成功的用户，获取spring security用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userName = userDetails.getUsername();
        QueryWrapper<AoaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        AoaUser aoaUser = aoaUserService.getOne(queryWrapper);
        Integer userId = aoaUser.getUserId();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String nowdate = sdf.format(date);
        // 判断这天期是星期几
        SimpleDateFormat sdf3 = new SimpleDateFormat("EEEE");
        // 截取时分
        SimpleDateFormat sdf4 = new SimpleDateFormat("HH:mm");
        // 截取时分秒
        SimpleDateFormat sdf5 = new SimpleDateFormat("HH:mm:ss");
        // 一周当中的星期几
        String weekofday = sdf3.format(date);
        // 时分
        String hourmin = sdf4.format(date);
        // 时分秒
        String hourminsec = sdf5.format(date);
        System.out.println("星期" + weekofday + "时分" + hourmin + "时分秒" + hourminsec);
        System.out.println(date);
        Integer attendsId = null;

        //查找用户当天所有记录
        Integer count = iAoaAttendsListService.countrecord(nowdate,userId);
        if (hourminsec.compareTo(end) > 0) {
            // 在17点之后签到无效
            System.out.println("----不能签到");
            model.addAttribute("error", "1");
        }
        if(hourminsec.compareTo("05:00:00") <0){
            //在凌晨5点之前不能签到
            System.out.println("----不能签到");
            model.addAttribute("error", "2");
        }
        else if((hourminsec.compareTo("05:00:00") >0)&&(hourminsec.compareTo(end) <0)){
            // 一个用户一天只能有两条记录
            if (count == 0) {
                if (hourminsec.compareTo(end) < 0) {
                    // 没有找到当天的记录表示此次点击是上班 用来判断该记录的类型
                    // 上班id8
                    type = 1;
                    // 上班就只有迟到和正常
                    if (hourminsec.compareTo(start) > 0) {
                        // 迟于规定时间 迟到
                        status = 1;
                    } else if (hourminsec.compareTo(start) < 0) {
                        //正常
                        status = 0;
                    }
                    aoaAttendsList.setType(type);
                    aoaAttendsList.setStatus(status);
                    aoaAttendsList.setAttendsTime(date);
                    aoaAttendsList.setAttendHmtime(hourmin);
                    aoaAttendsList.setWeekOfday(weekofday);
                    aoaAttendsList.setAttendsIp(attendIp);
                    aoaAttendsList.setAoaUser(aoaUser);
                    aoaAttendsList.setAttendsUserId(userId);
                    iAoaAttendsListService.save(aoaAttendsList);
                }
            }
            if (count == 1) {
                // 找到当天的一条记录就表示此次点击是下班
                type = 2;
                // 下班只有早退和正常
                if (hourminsec.compareTo(end) > 0) {
                    // 在规定时间下班--正常
                    status = 0;
                } else if (hourminsec.compareTo(end) < 0) {
                    // 在规定时间前下班--早退
                    status = 2;
                }
                aoaAttendsList.setType(type);
                aoaAttendsList.setStatus(status);
                aoaAttendsList.setAttendsTime(date);
                aoaAttendsList.setAttendHmtime(hourmin);
                aoaAttendsList.setWeekOfday(weekofday);
                aoaAttendsList.setAttendsIp(attendIp);
                aoaAttendsList.setAoaUser(aoaUser);
                aoaAttendsList.setAttendsUserId(userId);
                iAoaAttendsListService.save(aoaAttendsList);
            }
            if (count >= 2) {
                // 已经是下班的状态 count>=2就是修改考勤时间了
                if (hourminsec.compareTo(end) > 0) {
                    // 最近一次签到晚于规定时间下班--正常
                    status = 0;
                } else if (hourminsec.compareTo(end) < 0) {
                    // 最近一次签到早于规定时间早下班--早退
                    status = 2;
                }
                attendsId = iAoaAttendsListService.findoffworkid(nowdate,userId);
                AoaAttendsList attends = iAoaAttendsListService.getById(attendsId);

                attends.setAttendsIp(attendIp);
                attends.setAttendsTime(date);
                attends.setAttendHmtime(hourmin);
                attends.setStatus(status);
                iAoaAttendsListService.updateById(attends);
//                iAoaAttendsListService.save(attendsList1);
//                iAoaAttendsListService.updatetime(date,hourmin,status,attendsId);
//                AoaAttendsList lastestAttends = iAoaAttendsListService.findlastest(nowdate,userId);
//                model.addAttribute("attends",lastestAttends);
            }
        }
        // 显示用户当天最新的记录
        AoaAttendsList aList = iAoaAttendsListService.findlastest(nowdate,userId);
       // TypeDictUtils typeDictUtils = null;
        if (aList != null) {
           // String  typeName = typeDictUtils.getTypeName(model1,value);
            String typeName = typeListMapper.findTypeName(aList.getType());
            model.addAttribute("type", typeName);
        }
        model.addAttribute("attends", aList);
        return "systemcontrol/signin";
    }

    //加载考勤管理列表
    @RequestMapping("attendceatt")
    public String mangment(String userName, String page,Model model){
        //当前页
        int currentPage = 1;
        int pageCount = 10;
        //获取用户提交数据
        if (userName == null) {
            userName = "";
        }
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<AoaAttendsList> list = iAoaAttendsListService.findByAttendList(currentPage,pageCount,userName);
        int totalPage = iAoaAttendsListService.getTotalPage(pageCount,userName);
        //将数据包装到request对象中
        model.addAttribute("attendList", list);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("userName", userName);
        return "attendce/attendceview";
    }

    //考勤管理--删除
    @RequestMapping("attdelete")
    public String dataDelete(String aid){
        iAoaAttendsListService.removeById(aid);
        return "redirect:attendceatt";
    }

    //考勤管理--修改
    @RequestMapping("attendceedit")
    public String attendEdit(Model model,AoaAttendsList aoaAttendsList,Integer attendsId){
        QueryWrapper<AoaTypeList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("type_model","aoa_attends_list");
        List<AoaTypeList> typeList =  typeListService.list(queryWrapper1);
        QueryWrapper<AoaStatusList> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("status_model","aoa_attends_list");
        List<AoaStatusList> statusList = statusListService.list(queryWrapper2);
        if (attendsId != null){
          aoaAttendsList =iAoaAttendsListService.findById(attendsId);
        }
        model.addAttribute("aoaAttendsList",aoaAttendsList);
        model.addAttribute("typeList",typeList);
        model.addAttribute("statusList",statusList);
        return "attendce/attendceedit";
    }

    //考勤管理--保存
    @RequestMapping("attendcesave")
    public String saveAttend(AoaAttendsList aoaAttendsList, HttpServletRequest request){
        iAoaAttendsListService.saveAttend(aoaAttendsList,request);
        return "redirect:/attendceatt";
    }

    //加载我的考勤列表
    @RequestMapping("attendcelist")
    public String attendlist(String page, Model model, @SessionAttribute("userId") Integer userId){
        //读取当前登录成功的用户，获取spring security用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userName = userDetails.getUsername();
        //当前页
        int currentPage = 1;
        int pageCount = 5;
        //获取用户提交数据
        if (userName == null) {
            userName = "";
        }
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<AoaAttendsList> list = iAoaAttendsListService.findAttendById(currentPage,pageCount,userName);
        int totalPage = iAoaAttendsListService.getMyTotal(pageCount,userName);
        //将数据包装到request对象中
        model.addAttribute("myAttendList", list);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("userName", userName);
        return "attendce/attendcelist";
    }

    //周报表
    @RequestMapping("attendceweek")
    public String weekattend(String page,Model model,AoaAttendsList aoaAttendsList){
        //读取当前登录成功的用户，获取spring security用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userName = userDetails.getUsername();
        AoaUser aoaUser = aoaUserService.findUserByName(userName);
        Integer fatherId = aoaUser.getUserId();
        //当前页
        int currentPage = 1;
        int pageCount = 10;
        //获取用户提交数据
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<AoaAttendsList> list = iAoaAttendsListService.findByParentId(currentPage,pageCount,userName);
        int totalPage = iAoaAttendsListService.getEmpTotal(pageCount,fatherId);
        //将数据包装到request对象中
        model.addAttribute("weekList", list);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("userName",userName);
        return "attendce/weektable";
    }

    //周报表--修改类型
    @RequestMapping("attendceedit2")
    public String weekEdit(Model model,AoaAttendsList aoaAttendsList,Integer attendsId){
        QueryWrapper<AoaTypeList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("type_model","aoa_attends_list");
        List<AoaTypeList> typeList =  typeListService.list(queryWrapper1);
        QueryWrapper<AoaStatusList> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("status_model","aoa_attends_list");
        List<AoaStatusList> statusList = statusListService.list(queryWrapper2);
        if (attendsId != null ){
            aoaAttendsList =iAoaAttendsListService.findById(attendsId);
        }
        model.addAttribute("aoaAttendsList",aoaAttendsList);
        model.addAttribute("typeList",typeList);
        model.addAttribute("statusList",statusList);
        return "attendce/attendceedit2";
    }

    //周报表--保存修改
    @RequestMapping("saveweekattend")
    public String saveWeekAttend(AoaAttendsList aoaAttendsList, HttpServletRequest request){
        iAoaAttendsListService.saveAttend(aoaAttendsList,request);
        return "redirect:/attendceweek";
    }

    //月报表
    @RequestMapping("attendcemonth")
    public String monthattend(Model model,String page){
        //读取当前登录成功的用户，获取spring security用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userName = userDetails.getUsername();
        AoaUser aoaUser = aoaUserService.findUserByName(userName);
        Integer fatherId = aoaUser.getUserId();
        //当前页
        int currentPage = 1;
        int pageCount = 10;
        //获取用户提交数据
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<AoaAttendsList> list = iAoaAttendsListService.findByParentId(currentPage,pageCount,userName);
        int totalPage = iAoaAttendsListService.getEmpTotal(pageCount,fatherId);
        int findcoutn1 = attendsListMapper.findcoutn1(fatherId);
        int findcoutn2 = attendsListMapper.findcoutn1(fatherId);
        int findcoutn3 = attendsListMapper.findcoutn1(fatherId);
        int findcoutn4 = attendsListMapper.findcoutn1(fatherId);
        int findcoutn5 = attendsListMapper.findcoutn1(fatherId);
        int findcoutn6 = attendsListMapper.findcoutn1(fatherId);
        //将数据包装到request对象中
        model.addAttribute("monthList", list);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("userName",userName);
        model.addAttribute("findcoutn1",findcoutn1);
        model.addAttribute("findcoutn2",findcoutn2);
        model.addAttribute("findcoutn3",findcoutn3);
        model.addAttribute("findcoutn4",findcoutn4);
        model.addAttribute("findcoutn5",findcoutn5);
        model.addAttribute("findcoutn6",findcoutn6);
        return "attendce/monthtable";
    }

}
